//
//  ErandApproveListViewController.m
//  KIASupervisory
//
//  Created by tan_xin on 14-7-7.
//  Copyright (c) 2014年 MyCompany. All rights reserved.
//

#import "ErandApproveListViewController.h"
#import "ErandDetailListViewController.h"
#import "RejectViewController.h"

@interface ErandApproveListViewController () <RejectViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *contentView;

@property (nonatomic, strong) NSMutableArray *applyList;

- (IBAction)rejectAllApplyAction:(id)sender;
- (IBAction)agreeAllApplyAction:(id)sender;
@end

@implementation ErandApproveListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.applyList = [NSMutableArray array];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    
    self.showLeftBtn = YES;
    self.showRightBtn = NO;
    
    self.title = @"出差申请列表";
    [super viewWillAppear:animated];
    
    [self performSelector:@selector(getDudaoErandApplyList) withObject:nil afterDelay:0.3];
}

- (void)refreshViewByReloadData {
    [self getDudaoErandApplyList];
}

- (void)leftNavItemAction:(id)sender {
    AppDelegate *dele = [AppDelegate sharedDelegate];
    DDMenuController *menuVC = dele.ddLeftMenu;
    [menuVC showLeft:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)getDudaoErandApplyList {
    if (!self.isRefreshing) {
        self.isRefreshing = YES;
        [self.applyList removeAllObjects];
        
        UserInfo *user = [UserInfo instance];
        NSString *gonghao = [user.info objectForKeyOrNil:@"yhm"];
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               gonghao,@"gh", nil];
        [self.networkManager requestWithMethod:showUserInfoIfHaveBusiness parameter:param delegate:self];
        [self.HUD show:YES];
    }
    
}


- (IBAction)rejectAllApplyAction:(id)sender {
    if ([self.applyList count] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"您确认审批驳回全部的出差申请吗？"
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"确定", nil];
        alert.tag = 10003;
        [alert show];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"暂无数据"
                                                       delegate:self
                                              cancelButtonTitle:nil
                                              otherButtonTitles:@"确定", nil];
        [alert show];
    }

}


- (IBAction)agreeAllApplyAction:(id)sender {
    if ([self.applyList count] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                    message:@"您确认审批通过全部的出差申请吗？"
                                                   delegate:self
                                          cancelButtonTitle:@"取消"
                                          otherButtonTitles:@"确定", nil];
        alert.tag = 10002;
        [alert show];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"暂无数据"
                                                       delegate:self
                                              cancelButtonTitle:nil
                                              otherButtonTitles:@"确定", nil];
        [alert show];
    }
   
}


#pragma mark - UIAlerViewDelegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == alertView.firstOtherButtonIndex) {
        NSInteger tag = alertView.tag;
        if (tag == 10001) {
            
        } else if (tag == 10002) { //全部通过
            [self agreeAllApply];
        } else if (tag == 10003) {
            [self rejectAllApply];
        }
    }
}

- (void)agreeAllApply {
    UserInfo *user = [UserInfo instance];
    NSString *gonghao = [user.info objectForKeyOrNil:@"yhm"];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           gonghao,@"gh", nil];
        [self.networkManager requestWithMethod:allTongGuoApply parameter:param delegate:self];
        [self.HUD show:YES];
   
}


- (void)rejectAllApply {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Leader" bundle:nil];
    RejectViewController *rejectVC = (RejectViewController *)[storyboard instantiateViewControllerWithIdentifier:@"RejectViewController"];
    rejectVC.delegate = self;
    [self addChildViewController:rejectVC];
    [self.view addSubview:rejectVC.view];
    
}

#pragma mark - RejectViewDelegate
- (void)reject:(RejectViewController *)rejectVC willRejctWithReason:(NSString *)content {
    [self rejectAllApplyWithReason:content];
}


- (void)rejectAllApplyWithReason:(NSString *)reason {

        UserInfo *user = [UserInfo instance];
        NSString *gonghao = [user.info objectForKeyOrNil:@"yhm"]; //领导工号
        //NSString *gonghao = [self.dudaoInfo objectForKeyOrNil:@"gh"]; //督导工号
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               reason,@"bhly",
                               gonghao,@"gh", nil];
        [self.networkManager requestWithMethod:allRejectApply parameter:param delegate:self];
        [self.HUD show:YES];
}

#pragma mark - NetworkManagerDelegate
- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    [self endRefresh];
    self.isRefreshing = NO;
    
    if ([data isKindOfClass:[NSDictionary class]]) {
        int code = [[data objectForKeyOrNil:@"code"] integerValue];
        if (code == 0) {
            [self.applyList removeAllObjects];
            
            if ([data count] > 0) {
                id dataObject = [data objectForKeyOrNil:@"data"];
                if ([dataObject isKindOfClass:[NSArray class]]) {
                    [self.applyList addObjectsFromArray:dataObject];
                }
            }
            
        } else {
            NSString *msg = [data objectForKeyOrNil:@"msg"];
            if ([msg  length] == 0) {
                msg = @"出差申请列表获取失败，请稍后重试";
            }
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:msg
                                                           delegate:nil
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
            [alert show];
        }
        
        if (methodId == allTongGuoApply) { //全部通过
            
            if ([data isKindOfClass:[NSDictionary class]]) {
                id dataObject = [data objectForKeyOrNil:@"data"];
                NSInteger resultCode = [[dataObject objectForKeyOrNil:@"result"] integerValue];
                if (resultCode == 1) {
                    [self showAlertViewWithMessage:@"出差申请审批成功"];
//                    [self performSelector:@selector(leftNavItemAction:) withObject:nil afterDelay:0.9];
                }
            }
        } else if (methodId == allRejectApply) { //全部驳回
            if ([data isKindOfClass:[NSDictionary class]]) {
                id dataObject = [data objectForKeyOrNil:@"data"];
                NSInteger resultCode = [[dataObject objectForKeyOrNil:@"reslut"] integerValue];
                if (resultCode == 1) {
                    [self showAlertViewWithMessage:@"出差申请全部驳回成功"];
//                    [self performSelector:@selector(leftNavItemAction:) withObject:nil afterDelay:0.9];
                }
            }
        }

        
        [self.tableView reloadData];
    }
    
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    [self.HUD hide:YES];
    [self endRefresh];
    self.isRefreshing = NO;
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    
    NSInteger code = error.code;
    if (code != 1) {
        if ([msg length] == 0) {
            if (methodId == showUserInfoIfHaveBusiness) {
                msg = @"出差申请列表获取失败，请稍后重试";
            } else if (methodId == examineApply) {
                msg = @"出差申请审批失败，请稍后重试";
            } else if (methodId == rejectAllApplyList) {
                msg = @"出差申请全部驳回失败，请稍后重试";
            }
            
        }
    }
    if ([msg length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
    
    [self.tableView reloadData];
    
    
    
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    [self endRefresh];
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.applyList count];
//    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"ErrandsApproveCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        
    }
    
    UILabel *userIDLbl = (UILabel *)[cell.contentView viewWithTag:100];
    UILabel *userNameLbl = (UILabel *)[cell.contentView viewWithTag:101];
    UILabel *zhiweiLbl = (UILabel *)[cell.contentView viewWithTag:102];
    UILabel *dateLbl = (UILabel *)[cell.contentView viewWithTag:103];
    UIButton *statusBtn = (UIButton *)[cell.contentView viewWithTag:104];
    
    NSInteger row = indexPath.row;
    
    if ([self.applyList count] > row) {
        NSDictionary *cellData = [self.applyList objectAtIndex:row];
        
        NSString *dudaoName = [cellData objectForKeyOrNil:@"xm"];
        NSString *dudaoCode = [cellData objectForKeyOrNil:@"gh"];
        NSString *dudaoDept = [cellData objectForKeyOrNil:@"zw"];
        NSString *time = [cellData objectForKeyOrNil:@"ccsj"];
        if ([dudaoName isKindOfClass:[NSNull class]] || dudaoName == nil) {
            dudaoName = @"";
        }
        if ([dudaoCode isKindOfClass:[NSNull class]] || dudaoCode == nil) {
            dudaoCode = @"";
        }
        if ([dudaoDept isKindOfClass:[NSNull class]] || dudaoDept == nil) {
            dudaoDept = @"";
        }
        if ([time isKindOfClass:[NSNull class]] || time == nil) {
            time = @"";
        }
        
        userIDLbl.text = dudaoCode;
        userNameLbl.text = dudaoName;
        zhiweiLbl.text = dudaoDept;
        dateLbl.text = time;
        
        BOOL rejected = [[cellData objectForKeyOrNil:@"sfbh"] boolValue]; //是否驳回
        BOOL passed = [[cellData objectForKeyOrNil:@"shzt"] boolValue]; //申请状态
        BOOL submitted = [[cellData objectForKey:@"sftj"] boolValue]; //是否已经提交
        
        if (rejected) {
            [statusBtn setTitle:@"驳回" forState:UIControlStateNormal];
            [statusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [statusBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
            [statusBtn setBackgroundImage:[UIImage imageNamed:@"tip_驳回.png"] forState:UIControlStateNormal];
        } else {
            if (passed) { //通过
                [statusBtn setTitle:@"已通过" forState:UIControlStateNormal];
                [statusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [statusBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
                [statusBtn setBackgroundImage:[UIImage imageNamed:@"tip_通过.png"] forState:UIControlStateNormal];
            } else if (submitted) { //待审核
                [statusBtn setTitle:@"待审核" forState:UIControlStateNormal];
                [statusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [statusBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
                [statusBtn setBackgroundImage:[UIImage imageNamed:@"tip_待审核.png"] forState:UIControlStateNormal];
            } else { //未通过
                [statusBtn setTitle:@"未通过" forState:UIControlStateNormal];
                [statusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [statusBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
                [statusBtn setBackgroundImage:[UIImage imageNamed:@"tip_未通过.png"] forState:UIControlStateNormal];
            }
        }
    }
    
    return cell;
    
}

#pragma mark - UITableViewDelegate methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 60.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Leader" bundle:nil];
    ErandDetailListViewController *detailList = (ErandDetailListViewController *)[storyboard instantiateViewControllerWithIdentifier:@"LeaderApproveDetailList"];
    NSInteger row = indexPath.row;
    
    if ([self.applyList count] > row) {
        NSDictionary *cellData = [self.applyList objectAtIndex:row];
        detailList.dudaoInfo = cellData;
    }
    [self.navigationController pushViewController:detailList animated:YES];
}

@end
